package com.zy.utils;

import cn.hutool.core.lang.Snowflake;

import java.util.List;

/**
 * @program: shopping153_cloud
 * @description:
 * @author: zy
 * @create: 2025-08-20 14:10
 */
public class SnowFlakeIdGenerator {

    private final long workerId;
    private final long dataCenterId;
    private final long sequence;

    private final Snowflake snowflake;

    public SnowFlakeIdGenerator(long dataCenterId, long workerId) {
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
        this.sequence = 0L;

        this.snowflake = new Snowflake(workerId,dataCenterId);
    }

    /**
     * 只生成一个id号, 注意: 这个方法是线程安全的
     * @return
     */
    public synchronized long nextId(){
//        boolean a=true;
//        if(  a  ){
//            throw new RuntimeException("出异常了!");
//        }
        return snowflake.nextId();
    }

    private final int batchMaxSize=1000;   //最多每次生成1000个id号

    /**
     * 批量生成多个id号,
     * @param size
     * @return
     */
    public List<Long> nextIdBatch(int size){
        if(size>batchMaxSize){
            size=batchMaxSize;
        }
        List<Long> idList = new java.util.ArrayList<>();
        for (int i = 0; i < size; i++) {
            idList.add(nextId());
        }
        return idList;
    }

    /**
     *  解析时间戳
     */
    public long parseIdToTime(   long id ){
        return snowflake.getGenerateDateTime( id );
    }

    /**
     *  解析数据中心ID
     */
    public long parseIdToDatacenterId(long id) {
        return snowflake.getDataCenterId(id );
    }
    /**
     *  解析workerId
     */
    public long parseIdToWorkerId(long id) {
        return snowflake.getWorkerId( id );
    }


//    public static void main(String[] args) {
//        SnowFlakeIdGenerator snowFlakeIdGenerator = new SnowFlakeIdGenerator(0L, 1L);
//        long id = snowFlakeIdGenerator.nextId();
//        System.out.println(id);
//        System.out.println(snowFlakeIdGenerator.parseIdToTime(id));
//        System.out.println(snowFlakeIdGenerator.parseIdToDatacenterId(id));
//        System.out.println(snowFlakeIdGenerator.parseIdToWorkerId(id));
//    }

}
